import { config } from '@vue/test-utils';
import { IonicVue } from '@ionic/vue';
import { createRouter, createWebHistory } from '@ionic/vue-router';

// 全局测试配置
beforeAll(() => {
  // 模拟 HarmonyOS 环境
  Object.defineProperty(window, 'HarmonyOS', {
    value: true,
    writable: true
  });

  Object.defineProperty(window, 'HarmonyBridge', {
    value: {
      camera: {
        open: jest.fn().mockResolvedValue({ success: true }),
        takePhoto: jest.fn().mockResolvedValue({
          webPath: 'mock-photo-path.jpg',
          format: 'jpeg'
        }),
        close: jest.fn().mockResolvedValue({ success: true })
      },
      storage: {
        setItem: jest.fn().mockResolvedValue({ success: true }),
        getItem: jest.fn().mockResolvedValue({ value: 'mock-value' }),
        removeItem: jest.fn().mockResolvedValue({ success: true })
      },
      permissions: {
        request: jest.fn().mockResolvedValue({ granted: true }),
        check: jest.fn().mockResolvedValue({ granted: true })
      }
    },
    writable: true
  });

  // 模拟 Capacitor
  Object.defineProperty(window, 'Capacitor', {
    value: {
      isNativePlatform: () => false,
      getPlatform: () => 'web'
    },
    writable: true
  });

  // 模拟 navigator
  Object.defineProperty(navigator, 'userAgent', {
    value: 'Mozilla/5.0 (compatible; HarmonyOS)',
    writable: true
  });
});

// Vue Test Utils 全局配置
config.global.plugins = [IonicVue];

// 创建模拟路由器
const mockRouter = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', component: { template: '<div>Home</div>' } },
    { path: '/login', component: { template: '<div>Login</div>' } }
  ]
});

config.global.mocks = {
  $router: mockRouter,
  $route: {
    path: '/',
    params: {},
    query: {},
    meta: {}
  }
};

// 全局存根
config.global.stubs = {
  'ion-icon': true,
  'ion-button': true,
  'ion-content': true,
  'ion-header': true,
  'ion-toolbar': true,
  'ion-title': true,
  'ion-page': true
};

// 模拟 console 方法（避免测试时的日志输出）
global.console = {
  ...console,
  log: jest.fn(),
  warn: jest.fn(),
  error: jest.fn()
};

// 模拟 localStorage
const localStorageMock = {
  getItem: jest.fn(),
  setItem: jest.fn(),
  removeItem: jest.fn(),
  clear: jest.fn()
};
Object.defineProperty(window, 'localStorage', {
  value: localStorageMock
});

// 模拟 sessionStorage
const sessionStorageMock = {
  getItem: jest.fn(),
  setItem: jest.fn(),
  removeItem: jest.fn(),
  clear: jest.fn()
};
Object.defineProperty(window, 'sessionStorage', {
  value: sessionStorageMock
});

// 模拟 fetch
global.fetch = jest.fn(() =>
  Promise.resolve({
    ok: true,
    json: () => Promise.resolve({}),
    text: () => Promise.resolve('')
  })
) as jest.Mock;

// 清理函数
afterEach(() => {
  jest.clearAllMocks();
  localStorageMock.clear();
  sessionStorageMock.clear();
});